package com.example.demo.lock;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

/**
 * 可中断,如果持有锁的线程一直没有释放，
 * 其他线程可以不用浪费时间在等待获取锁
 * @author cici
 */
@Slf4j
public class ReentrantLock2 {

    private static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                log.info("尝试获取锁");
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.info("没有获取到锁，返回");
                return;
            }
            try {
                log.info("获取到锁");
            }finally {
                lock.unlock();
            }
        },"t1");
        //没释放锁
        lock.lock();
        try {
            sleep(100);
            log.info("主线程代码执行。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
//            lock.unlock();
        }
        thread.start();
        log.info("打断t1,此时t1还在等待");
        thread.interrupt();
    }
}
